package com.linkage.usercenter.controller;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import com.linkage.common.base.ResponseInfo;
import com.linkage.common.constant.CommonSysConstant;
import com.linkage.common.exception.CustomException;
import com.linkage.common.exception.ServiceException;
import com.linkage.usercenter.config.TokenCheckException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @program: jingbao-202004
 * @description: 全局异常处理
 * @author: chengshaofeng
 * @create: 2020-05-25 21:41
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(ValidateException.class)
    @ResponseBody
    public String ValidateExceptionHandler(ValidateException e, HttpServletResponse response) {
        return ResponseInfo.error(e.getMessage()).toString();
    }

    @ExceptionHandler(TokenCheckException.class)
    @ResponseBody
    public String TokenCheckExceptionHandler(TokenCheckException e, HttpServletResponse response) {
        return ResponseInfo.tokenError(e.getMessage()).toString();
    }

    @ExceptionHandler
    @ResponseBody
    public String exceptionHandler(Exception e, HttpServletResponse response) {
        logger.error("未知异常：" + e.getMessage(),e);
        return ResponseInfo.error("系统异常，请联系管理员！" ).toString();
    }
    /**
     * 基础异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseInfo ServiceException(ServiceException e) {
        logger.error(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
        return ResponseInfo.error(e.getMessage());
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public ResponseInfo businessException(CustomException e) {
        logger.error(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
        if (StrUtil.isEmpty(e.getCode()))
        {
            return ResponseInfo.error(CommonSysConstant.CODE_ONE, e.getMessage());
        }
        return ResponseInfo.error(e.getCode(), e.getMessage());
    }

}


